package pl.edu.uj.tcs.blef.protocol;

import java.io.PrintWriter;
import java.net.Socket;

import pl.edu.uj.tcs.blef.server.Client;
import pl.edu.uj.tcs.blef.server.Table;

public class MsgRequestHandler extends AbstractTableHandler {

	public MsgRequestHandler(Table table) {
		super(table);
	}

	@Override
	public void handle(Request request, Socket socket) {
		System.out.println("Handling " + request.message + " request from " + socket.getInetAddress().getHostAddress());
		MsgRequest ctr = (MsgRequest)request;
		Client client = null;
		for(Client c: table.getPlayers()){
			if(c.getSocket().equals(socket)){
				client = c;
				break;
			}
		}
		
		for(Client c: table.getAwaitingPlayers()){
			if(c.getSocket().equals(socket)){
				client = c;
				break;
			}
		}
		
		for(Client c: table.getLostPlayers()){
			if(c.getSocket().equals(socket)){
				client = c;
				break;
			}
		}
		
		if(client == null){
			try {
				Request r = new UnknownRequestErrorFactory().build(null, new NullRequestHandler());
				r.send(new PrintWriter(socket.getOutputStream()));
				return;
			} catch (Exception e){}
		}
		
		StringBuilder sb = new StringBuilder();
		sb.append("BROADCAST "+ client.getNick() + '\n');
		sb.append(ctr.getMsg());
		for(Client c: table.getPlayers()){
			try {
				String[] param = new String[1]; param[0] = sb.toString();
				Request r = new OKRequestFactory().build(param, new NullRequestHandler());
				r.send(new PrintWriter(c.getSocket().getOutputStream()));
			} catch (Exception e){}
		}
		
		for(Client c: table.getAwaitingPlayers()){
			try {
				String[] param = new String[1]; param[0] = sb.toString();
				Request r = new OKRequestFactory().build(param, new NullRequestHandler());
				r.send(new PrintWriter(c.getSocket().getOutputStream()));
			} catch (Exception e){}
		}
		
		for(Client c: table.getLostPlayers()){
			try {
				String[] param = new String[1]; param[0] = sb.toString();
				Request r = new OKRequestFactory().build(param, new NullRequestHandler());
				r.send(new PrintWriter(c.getSocket().getOutputStream()));
			} catch (Exception e){}
		}
	}

}
